package com.tal.live.utils.trace;


import com.tal.live.utils.context.SpringContextHolder;
import com.tal.live.utils.web.RequestHolder;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.util.UUID;

/**
 * <Description>
 *
 * @author xianliru@100tal.com
 * @version 1.0
 * @createDate 2019/10/09 16:40
 */

public class TraceIdConfig {

    public static final String REQUEST_ID_KEY = "requestId";

    public static final String PROJECT_PID = "pid";

    public static final String PROJECT_VERSION = "version";

    public static final String ADDRESS_IP = "IP";

    private static Environment env = SpringContextHolder.getBean(Environment.class);


    public static String traceId() {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        String requestId = null;
        String parameterRequestId = request.getParameter(REQUEST_ID_KEY);
        String headerRequestId = request.getHeader(REQUEST_ID_KEY);

        if (parameterRequestId == null && headerRequestId == null) {
            requestId = UUID.randomUUID().toString();
        } else {
            requestId = parameterRequestId != null ? parameterRequestId : headerRequestId;
        }
        return requestId;
    }

    public static String getProjectVersion(){
       return env.getProperty("info.version");
    }

    public static String getProjectPid(){
        String name = ManagementFactory.getRuntimeMXBean().getName();
        // get pid
        String pid = name.split("@")[0];
        return pid;
    }
}
